package com.funtl.screw.common.route.feign;

import cn.hutool.core.util.StrUtil;
import com.funtl.screw.common.core.constant.CommonConstants;
import com.funtl.screw.common.core.util.ServiceWebUtils;
import com.funtl.screw.common.route.support.GrayRouteVersionContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * feign 请求VERSION 传递
 *
 * <p>Title GrayFeignRequestInterceptor</p >
 * <p>Description  </p >
 *
 * @author Lusifer
 * @version 1.0.0
 * @since 2022/11/7 10:30
 */
@Slf4j
public class GrayRouteFeignRequestInterceptor implements RequestInterceptor {

    /**
     * Called for every request. Add data using methods on the supplied
     * {@link RequestTemplate}.
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        String reqVersion = ServiceWebUtils.getRequest() != null ? ServiceWebUtils.getRequest().getHeader(CommonConstants.VERSION)
                : GrayRouteVersionContextHolder.getVersion();

        if (StrUtil.isNotBlank(reqVersion)) {
            log.debug("feign gray add header version :{}", reqVersion);
            template.header(CommonConstants.VERSION, reqVersion);
        }
    }
}
